/**
 * @description 组合概览事件列表
 * @author muisuidaan
 */
import React, { useEffect, useState } from "react";

// import * as echarts from "echarts";

import Area from "@/components/EchartsComponents/Area";
import LineAndBar from "@/components/EchartsComponents/LineAndBar";
import LineAndPoint from "@/components/EchartsComponents/LineAndPoint";

import MultiLine from "@/components/EchartsComponents/Line/MultiLine";
import Bar from "@/components/EchartsComponents/Bar/stackBar";


import EventTable from "@/components/Table";
import EventDetail from "@/components/FOF/EventDetail";
import EventEmpty from "@/components/FOF/EventEmpty";

import { queryFundEvent } from "@/pages/PortfolioOverview/portfolio";
import { queryFundEventList } from "../../portfolio";
import { Spin } from "antd";
import {infoChartProps,DataProps} from "@/pages/StockFixedAssets";

import {
  getBaseColors,
  getExpandColors,
  getEchartsTypes,
} from "@/utils/echarts";
import {
  getUrlParam,
  getDataFromObject,
  getMergeRecordFromTable,
} from "@/utils/utils";
import { getColumnsFromEventCode } from "@/utils/const";

import styles from "./index.less";
import classNames from "classnames";
import dayjs from 'dayjs';
export interface itemProps {
  [key: string | number]: number | string | null;
}
interface eventProps extends infoChartProps{
  xaxis?: Array<string>;
  yaxis?: Array<DataProps>;
  fundManagerList?:Array<itemProps>;
  cycleDTOS?:Array<itemProps>;
  creditAbnormalDetailList?:Array<itemProps>;
  dtoList?:Array<itemProps>;
  diviDendList?:Array<itemProps>;
  subAndRedeDTO?:{
    subFeeList?:Array<itemProps>;
    detailList?:Array<itemProps>;
    remarkList?:Array<itemProps>;
  }
  list?:Array<itemProps>;
}
export interface InfoProps{
  innerCode?:string|number;
  secuCode?:string|number;
  id?:string|number;
  fundLableList?:Array<itemProps>;
  secuAbbr?:string;
  eventCode:string;
  activeKey:string;
  remark?:string;
}
interface Props {
  visiable?: boolean;
  info: InfoProps;
  outId?: string; //跳转的事件id
  time?: string | number; // 重复点击一个内容时用这个来触发
  changeLoadState:(bool:boolean)=>void;
  outInfo: InfoProps;
  deleteTime:()=>void;
}
const legendStyle = {
  textStyle:{
    fontSize: 10,
    color: "#35425e",
    width: 48,
    lineHeight: 12,
    padding: [0, 0, -3, 2],
  },
  top:0
};
const EventDetailContainer = (props: any) => {
  const { event,outId,time ,changeLoadState,outInfo,deleteTime} = props || {};
  const { eventCode, innerCode, id, secuCode,open } = event || {};
  const [eventData, setEventData] = useState<eventProps>({});
  const [loading,setLoding] = useState(false);
  const [hasRequested, setHasRequested] = useState(false);

  const prevCountRef:any = React.useRef();

  
  
  useEffect(()=>{
    if(outId && outId==id &&hasRequested && time &&open == outId && outInfo?.activeKey == "all"){
      const _handleScroll = () => {
        const scroll_item = document.getElementById(outId);
        if (scroll_item) {
         
          // console.log(22222,scroll_item.offsetHeight)
          const offsetHeight = scroll_item.offsetHeight;
          const documentH = document.body.clientHeight;
          const compareH = documentH>(offsetHeight+300)?(documentH-offsetHeight-320):125;//需要兼顾小屏并且需要考虑元素本身的高度，如果展示不下则需要根据上面来展示
          if(scroll_item.offsetParent){
            scroll_item.offsetParent.scrollTop = scroll_item.offsetTop - compareH;
            changeLoadState(true);
            deleteTime&&deleteTime();
          }
          

          // console.log('scroll_item.offsetTop',scroll_item.offsetTop,scroll_item.offsetHeight,scroll_item.offsetParent.scrollHeight)
          //  - scroll_item.offsetHeight;
        }
      };
      //雨薇要求元素底部固定在可视区里，所以需要等元素打开后计算元素的高度
      setTimeout(() => {
        requestAnimationFrame(_handleScroll);
      }, 0);
    }

  },[outId,hasRequested,time])
  const getData = (params: InfoProps) => {
    setLoding(true);
    setHasRequested(false);
    queryFundEvent(params).then((res: any) => {
      if (res?.code === "0") {
        setEventData(getDataFromObject(res?.data || {}));
      }
      setLoding(false);
      setHasRequested(true);
      // console.log("res", res);
    });
  };
  useEffect(() => {
    getData(
      {
        innerCode: innerCode, //todo
        eventCode: eventCode,
      }
      // {
      //   "innerCode": 413267,
      //   "eventCode": "bond_deviate_valuation_positive_change"
      // },
      // {
      //   "innerCode": 4127,
      //   "eventCode": "bond_deviate_valuation_negative_change"
      // },
    );
  }, [eventCode, innerCode]);
  // console.log("eventData", eventData);

  const getRowClassName = (record, index) => {
    // console.log('record',record)
    let className = "";
    if (record.flag > 0) {
      className = "table_high_light";
    }
    if(record.rowSpan){
      className += "merge_row";
    }
    return className;
  };
  // console.log("event", event, "eventData", eventData,getEchartsTypes(eventCode));
  console.log('outInfo11111111111111',outInfo)
  return (
    <div key={id}>
      {event.open && (
        <Spin spinning={loading}>
          <EventDetail
            info={event}
            children={
              getEchartsTypes(eventCode)==="multiplue_line"?(
                <>
                {console.error('eventData',eventData)}
                  {eventData?.axis?.xaxis ? (
                    <div style={{ width: "100%", height: 156 }}>
                      <Area
                        gridStyle={{top:30}}
                        showLine={true}
                        notShowArea={true}
                        notShowStack={true}
                        idName={`overview-event-detail${secuCode}${eventCode}${id}${outInfo?.activeKey}8`}
                        xAxis={eventData?.axis?.xaxis}
                        data={
                          eventData?.axis?.yaxis?.length > 0
                            ? eventData?.axis?.yaxis
                            : []
                        }
                        legendStyle={legendStyle}
                        legend={
                          eventData?.axis?.yaxis?.length > 0
                            ? eventData?.axis?.yaxis.map(
                                (item: DataProps) => item.label
                              )
                            : []
                        }
                        color={[...getBaseColors(), ...getExpandColors()]}
                        notNeedSort={true}
                      />
                    </div>
                  ) : (
                    <EventEmpty title="暂无数据" />
                  )}

                  
                </>
              ):
              getEchartsTypes(eventCode)==="line_and_dot"?(
                <>
                  {eventData?.axis?.xaxis ? (
                    <div style={{ width: "100%", height: 156 }}>
                      <LineAndPoint
                        legendStyle={legendStyle}
                        idName={`overview-event-detail${secuCode}${eventCode}${id}${outInfo?.activeKey}9`}
                        xAxis={eventData?.axis?.xaxis}
                        data={
                          eventData?.axis?.yaxis?.length > 0
                            ? eventData?.axis?.yaxis
                            : []
                        }
                        legend={
                          eventData?.axis?.yaxis?.length > 0
                            ? eventData?.axis?.yaxis.map(
                                (item: DataProps) => item.label
                              )
                            : []
                        }
                      />
                    </div>
                  ) : (
                    <EventEmpty title="暂无数据" />
                  )}

                  
                </>
              ):
              getEchartsTypes(eventCode) === "line_and_bar" ? (
                <>
                  {eventData?.rateAxis?.xaxis ? (
                    <div style={{ width: "100%", height: 156 }}>
                      <LineAndBar
                        legendStyle={legendStyle}
                        idName={`overview-event-detail${secuCode}${eventCode}${id}${outInfo?.activeKey}2`}
                        xAxis={eventData?.rateAxis?.xaxis}
                        data={
                          eventData?.rateAxis?.yaxis?.length > 0
                            ? eventData?.rateAxis?.yaxis
                            : []
                        }
                        legend={
                          eventData?.rateAxis?.yaxis?.length > 0
                            ? eventData?.rateAxis?.yaxis.map(
                                (item: DataProps) => item.label
                              )
                            : []
                        }
                        // color={["#3457C4", "#E85C36"]} //上折线指定色
                      />
                    </div>
                  ) : (
                    <EventEmpty title="暂无数据" />
                  )}

                  {eventData?.predictedAxis?.xaxis ? (
                    <div style={{ width: "100%", height: 143 }}>
                      <Area
                        gridStyle={{top:30}}
                        showLine={true}
                        notShowArea={true}
                        notShowStack={true}
                        idName={`overview-event-detail${secuCode}${eventCode}${id}${outInfo?.activeKey}1`}
                        xAxis={eventData?.predictedAxis?.xaxis}
                        data={
                          eventData?.predictedAxis?.yaxis?.length > 0
                            ? eventData?.predictedAxis?.yaxis
                            : []
                        }
                        legendStyle={legendStyle}
                        legend={
                          eventData?.predictedAxis?.yaxis?.length > 0
                            ? eventData?.predictedAxis?.yaxis.map(
                                (item: DataProps) => item.label
                              )
                            : []
                        }
                        color={[...getBaseColors(), ...getExpandColors()]}
                        notNeedSort={true}
                      />
                    </div>
                  ) : (
                    <EventEmpty title="暂无数据" />
                  )}
                </>
              ) :getEchartsTypes(eventCode)==="bar"?(
                <>
                  {eventData?.axis?.xaxis ? (
                    <div style={{ width: "100%", height: 156 }}>
                      <Bar
                          gridStyle={{top:30}}
                          legendStyle={legendStyle}
                          isStack={false}
                          // percent={true}
                          idName={`overview-event-detail${secuCode}${eventCode}${id}${outInfo?.activeKey}7`}
                          xAxis={eventData?.axis.xaxis}
                          legend={eventData?.axis.yaxis.map(
                            (item: DataProps) => item.label
                          )}
                          data={eventData?.axis.yaxis}
                          color={[...getBaseColors(), ...getExpandColors()]}
                        />
                    </div>
                  ) : (
                    <EventEmpty title="暂无数据" />
                  )}

                  
                </>
              ): (
                <>
                  {getEchartsTypes(eventCode) === "line_and_area" &&
                    (eventData?.xaxis ? (
                      <div
                        className={styles.chart_echarts}
                        style={{ width: "100%", height: 196 }}
                      >
                        <MultiLine
                          percent
                          gridStyle={{top:30}}
                          legendStyle={legendStyle}
                          idName={`overview-event-detail${secuCode}${eventCode}${id}${outInfo?.activeKey}`}
                          xAxis={
                            (eventData?.xaxis &&
                              eventData?.xaxis.map((v) =>
                              dayjs(v).format("YYYY-MM-DD")
                              )) ||
                            []
                          }
                          legend={
                            (eventData?.yaxis &&
                              eventData?.yaxis.map((v) => v.label)) ||
                            []
                          }
                          data={(eventData?.yaxis && eventData?.yaxis) || []}
                          color={["#3457C4", "#E85C36"]}
                          areaList={eventData.cycleDTOS}
                        />
                      </div>
                    ) : (
                      <EventEmpty title="暂无数据" />
                    ))}
                  {getEchartsTypes(eventCode) === "area"&&
                    eventData?.xaxis?.length > 0 && (
                      <div
                        className={styles.chart_echarts}
                        style={{ width: "100%", height: 196 }}
                      >
                        <Area
                          gridStyle={{top:30}}
                          legendStyle={legendStyle}
                          showLine={true}
                          percent={true}
                          idName={`overview-event-detail${secuCode}${eventCode}${id}${outInfo?.activeKey}`}
                          xAxis={eventData?.xaxis}
                          data={
                            eventData?.yaxis?.length > 0 ? eventData?.yaxis : []
                          }
                          legend={
                            eventData?.yaxis?.length > 0
                              ? eventData?.yaxis.map((item: DataProps) => item.label)
                              : []
                          }
                          color={[...getBaseColors(), ...getExpandColors()]}
                        />
                      </div>
                    )}
                  {getEchartsTypes(eventCode) === "table" && (
                    <div
                      className={`event_simle_table list_table_with_border table_header_center`}
                    >
                      <EventTable
                        columns={getColumnsFromEventCode(eventCode)}
                        dataSource={{
                          records: eventData?.fundManagerList || [],
                        }}
                        scroll={true}
                        notShowPagination={true}
                        rowClassName={getRowClassName}
                      />
                    </div>
                  )}
                  {(getEchartsTypes(eventCode) === "special_table"||getEchartsTypes(eventCode) === "special_table2") && (
                    <div
                      className={classNames(`event_simle_table list_table_with_border table_header_center event_simle_table_special`,styles.text_ellicips_container,getEchartsTypes(eventCode) === "special_table2"?styles.special_table2_container:'')}
                    >
                      <EventTable
                        columns={getColumnsFromEventCode(eventCode)}
                        dataSource={{
                          records: eventData?.creditAbnormalDetailList || eventData?.list ||eventData?.dtoList ||[],
                        }}
                        scroll={true}
                        notShowPagination={true}
                        rowClassName={getRowClassName}
                      />
                    </div>
                  )}
                  {getEchartsTypes(eventCode) === "three_table" && (
                    <div className={styles.three_table_container}>
                      <div className={styles.left_container}>
                        <div
                          className={`event_simle_table list_table_with_border table_header_center`}
                        >
                          <EventTable
                            columns={
                              getColumnsFromEventCode(eventCode)
                                ? getColumnsFromEventCode(eventCode)[1]
                                : []
                            }
                            dataSource={{
                              records:
                                eventData?.subAndRedeDTO?.subFeeList || [],
                            }}
                            scroll={true}
                            notShowPagination={true}
                            rowClassName={getRowClassName}
                          />
                        </div>
                      </div>
                      <div className={styles.right_container}>
                        <div
                          className={`event_simle_table list_table_with_border table_header_center`}
                        >
                          <EventTable
                            columns={
                              getColumnsFromEventCode(eventCode)
                                ? getColumnsFromEventCode(eventCode)[2]
                                : []
                            }
                            dataSource={{
                              records:
                                eventData?.subAndRedeDTO?.detailList || [],
                            }}
                            scroll={true}
                            notShowPagination={true}
                            rowClassName={getRowClassName}
                          />
                          <div style={{ marginTop: 5 }}></div>
                          <EventTable
                            columns={
                              getColumnsFromEventCode(eventCode)
                                ? getColumnsFromEventCode(eventCode)[3]
                                : []
                            }
                            dataSource={{
                              records:
                                eventData?.subAndRedeDTO?.remarkList || [],
                            }}
                            scroll={true}
                            notShowPagination={true}
                            rowClassName={getRowClassName}
                          />
                        </div>
                      </div>
                    </div>
                  )}
                  {getEchartsTypes(eventCode) === "add_table" && (
                    <div
                      className={`event_simle_table list_table_with_border table_header_center add_table`}
                    >
                      <EventTable
                        columns={getColumnsFromEventCode(eventCode)}
                        dataSource={{
                          records:
                            getMergeRecordFromTable(
                              eventData?.diviDendList,
                              "year"
                            ) || [],
                        }}
                        scroll={true}
                        notShowPagination={true}
                        rowClassName={getRowClassName}
                      />
                    </div>
                  )}
                </>
              )
            }
          />
        </Spin>
      )}
    </div>
  );
};


const EventList = (props: Props) => {
  const { visiable, info, outId, time,changeLoadState,deleteTime } = props || {};
  const { innerCode, secuCode, id } = info || {};
  const [eventList, setEventList] = useState<Array<eventProps>>([]);
  const [hasRequested, setHasRequested] = useState(false);

  useEffect(() => {
    //打开跳转的事件详情
    // console.log("outId", outId);
    console.log(outId , hasRequested , eventList?.length > 0,visiable,time , info?.activeKey,info?.activeKey == "all");
    if (outId && hasRequested && eventList?.length > 0&&visiable&&time && info?.activeKey == "all") {
      
      //打开列表
      setEventList(
        eventList.map((item: any) => {
          // console.log("outId", outId, "item.id", item.id);
          return {
            ...item,
            open: outId == item.id ? outId : item.open,
          };
        })
      );
      // console.log("outId", outId,hasRequested,eventList);

      // const _handleScroll = () => {
      //   const scroll_item = document.getElementById(outId);
      //   if (scroll_item) {
      //     scroll_item.offsetParent.scrollTop = scroll_item.offsetTop;
      //     console.log('scroll_item.offsetTop',scroll_item.offsetTop,scroll_item.offsetParent,scroll_item.offsetParent.scrollHeight)
      //     //  - scroll_item.offsetHeight;
      //   }
      // };
      // requestAnimationFrame(_handleScroll);
     
    }
  }, [outId, hasRequested, time,visiable,info?.activeKey]);

  useEffect(() => {
    setHasRequested(false);
    queryFundEventList({
      innerCode: innerCode,
      portfolioCode: getUrlParam("id"),
    }).then((res: any) => {
      if (res?.code === "0") {
        if (res?.data?.length > 0) {
          setEventList(res.data);
        } else {
          setEventList([]);
        }
        setHasRequested(true);
      }
    });
  }, [visiable]);

  const handleChangeStatus = (event: any) => {
    if (!event.id) return;
    setEventList(
      eventList.map((item: any) => ({
        ...item,
        open: event.id === item.id ? !item.open : item.open,
      }))
    );
  };

  return (
    <div className={styles.event_list_wrapper}>
      {eventList?.length > 0
        ? eventList.map((event: any) => (
            <div 
              id={event.id} 
              key={event.id} 
              className={styles.event_list_box} 
              
            >
              <div
                className={styles.event_list_container}
                onClick={() => {
                  handleChangeStatus(event);
                }}
              >
                <p
                  className={
                    event?.messageType == 1
                      ? styles.icon_warnning
                      : styles.icon_message
                  }
                ></p>
                <p
                  className={classNames(
                    styles.event_list_text,
                    event?.open ? styles.event_list_text_active : null
                  )}
                >
                  {event?.eventDate || "-"} {event?.eventHeader || "-"}
                </p>
                <p
                  className={classNames(
                    styles.show_button,
                    event.open ? styles.show_button_active : null
                  )}
                ></p>
              </div>
              {event?.open && (
                <EventDetailContainer
                  event={{
                    ...event,
                  }}
                  outId={outId}
                  outInfo={info}
                  time={time}
                  changeLoadState={changeLoadState}
                  deleteTime={deleteTime}
                />
              )}
            </div>
          ))
        : null}
    </div>
  );
};

export default EventList;
